import { ref, createApp, h } from 'vue'
import MessageToast from '../components/MessageToast.vue'

interface ToastOptions {
  type?: 'success' | 'error' | 'info'
  title: string
  message?: string
  duration?: number
  closable?: boolean
}

const toasts = ref<Array<{ id: number; component: any }>>([])
let toastId = 0

export const useToast = () => {
  const showToast = (options: ToastOptions) => {
    const id = ++toastId
    
    // 创建一个容器元素
    const container = document.createElement('div')
    document.body.appendChild(container)
    
    // 创建Vue应用实例
    const app = createApp({
      render() {
        return h(MessageToast, {
          ...options,
          onClose: () => {
            app.unmount()
            document.body.removeChild(container)
          }
        })
      }
    })
    
    // 挂载应用
    app.mount(container)
    
    return id
  }

  const success = (title: string, message?: string, duration = 3000) => {
    return showToast({ type: 'success', title, message, duration })
  }

  const error = (title: string, message?: string, duration = 5000) => {
    return showToast({ type: 'error', title, message, duration })
  }

  const info = (title: string, message?: string, duration = 3000) => {
    return showToast({ type: 'info', title, message, duration })
  }

  return {
    showToast,
    success,
    error,
    info
  }
}